package com.sx.frame.test;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.handler.WriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddress;

import java.util.ArrayList;
import java.util.List;

public class ExcelGenerator {

    public static void main(String[] args) {
        // 文件路径
        String fileName = "merged_cells.xlsx";

        // 创建表头数据列表
        List<List<String>> headData = new ArrayList<>();

        // 第一行表头数据
        List<String> firstHeadRow = new ArrayList<>();
        firstHeadRow.add("a");
        firstHeadRow.add("b"); // 这个列会被合并
        headData.add(firstHeadRow);

        // 第二行表头数据
        List<String> secondHeadRow = new ArrayList<>();
        for (int i = 1; i <= 11; i++) {
            secondHeadRow.add(String.valueOf(i));
        }
        headData.add(secondHeadRow);

        // 数据部分
        List<List<Object>> data = new ArrayList<>();
        for (int j = 0; j < 10; j++) { // 假设我们有10行数据
            List<Object> rowData = new ArrayList<>();
            for (int k = 0; k < 11; k++) {
                rowData.add((j + 1) * (k + 1)); // 示例数据
            }
            data.add(rowData);
        }

        // 写入Excel
        EasyExcel.write(fileName)
                .head(headData)
                .registerWriteHandler(new CellWriteHandler() {
                    public void afterSheetCreate(WriteSheetHolder writeSheetHolder, Sheet sheet) {
                        // 合并第一行的第二列到第十一列（索引为1到10）
                        CellRangeAddress cellRangeAddress = new CellRangeAddress(0, 0, 1, 10);
                        sheet.addMergedRegion(cellRangeAddress);
                    }
                })
                .sheet("Sheet1")
                .doWrite(data);
    }
}



